package cn.itcast.travel.domain;

import cn.itcast.travel.service.PayService;
import cn.itcast.travel.service.impl.PayServiceImp;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class PayController {
    private final String APP_ID = "2016103100781680";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpe320Uxi6gM62erlZLS2SUtPtXD3I75Rb/xrWHzq8qV19WEJMkTLFm30WUfVpKJYpGj8PNmSYhhCmPCI8aZHgZug5psnZN58KbEQSclY+aUVSV1YrNMsrIlMjxXWU/8e++ooL+maAVU/BJmYZHGRyEvzZBGZRI5JJJes8v4PH/wRzsq/YuNmBMZvDfyZN8j5XOlWSgRzYj+wF+HSApSE8DfBxz77FQRQZ6pM9Lqq/Nn2VF9QUbex2KLmz7krLRIDgsqMQIErFyDx9Onv2aMdUEYI2W8XQsk8rQ6Vqxic2T6j4kapY4bOz1iK3AS4zezV7DDKU961y7VL0avBFrEKlAgMBAAECggEANs5pawvIHl+S+S2cjHrwlrXUNJi0nirjdhB71CxLKUE3q1YEMpBts7tBaxtb2gK29Fm5dKjpRO1tquQdSh31f3SnuiT2dxjmhE9YgAKbYxlVwnfdtKEg5jT2X8X17RX9uQN56r+xr+RmoxZQw+QLk1wSifdDQw/WuXLarE1eRyjns6s6xdKmxATVUFpGwuoJJrO/axAf1gG+EURd2jUrCmtl6ja89Ns7Kbb5dv44pYx+c0ZYjUUgYtTsdxbfQk4JVJpPzvtEsCp3uIZ5sdQkfYBDY4EDJs/GOLAWXGj07FUWTy/kVocBAr05GK8Al+5jnG9XwOGJFFDiOUqElI2GzQKBgQDsU9ufAyqmXUk6gbDqhHRmQoQD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m8XHUBXxwQQQrU7kFfxeUNJxhej1LErYPazc677aoNDP3iQ6ceKJ/zx+vggb0uLZ/E6f8KRYK6gZ9uUEM5aIeauZFe+Kv08wxj3DnV7GTLRYE3eF0arJzaPKK7Svq5s0aMKFX+lnTiJVhU7HbJp8Oyq+QkClHTCazOs/1nDrPItaiCL7mRkleTJuZQ2+/m8LnFiT/ZDT6dd4QVgwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://www.scz.cn/travel/money/returnPly";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的s页面,可以不是公网地址
    private final String RETURN_URL = "https://www.scwyz.cn/travel/money/returnPly";
    private PayService payService=new PayServiceImp();
    /**
     * 支付方法
     * @param httpResponse
     * @throws IOException
     */
    public void alipay(HttpServletResponse httpResponse,String out_trade_no,String total_amount, String subject,String body) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 订单创建以后支付的方法
     * @param httpResponse
     * @param out_trade_no
     * @param subject
     * @param body
     * @throws IOException
     */
    public void alipay2(HttpServletResponse httpResponse,String out_trade_no, String subject,String body) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl("http://www.scwyz.cn/travel/userIndex.html");
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 验证支付是否成功
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws AlipayApiException
     */
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            //String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            //String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");


            //支付成功，修复支付状态
            //payService.updateById(Integer.valueOf(out_trade_no));
            payService.updateById(out_trade_no);
            return "ok";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }

    }

}

